<template>
  <a-directory-tree :tree-data="tree_data.treeList" v-model:expandedKeys="expandedKeys" @click="tree_click">
    <template #title="{ key: treeKey, title }">
      <a-dropdown :trigger="['contextmenu']">
        <span>{{ title }}</span>
        <template #overlay>
          <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)">
            <a-menu-item key="1">1st menu item</a-menu-item>
            <a-menu-item key="2">2nd menu item</a-menu-item>
            <a-menu-item key="3">3rd menu item</a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </template>
  </a-directory-tree>
</template>
<script>
import {defineComponent, watch, ref, reactive} from 'vue';
/**
 * 获取树结构
 * */
import {get_org_tree_list, get_org_tree_list_left} from "@/api/mechanism"

const treeData = [
  {
    title: '焊联工业有限公司',
    key: '0-0',
    children: [
      {
        title: '生产部',
        key: '0-0-0',
        children: [
          {
            title: '张三',
            key: '0-0-0-0',
          },
          {
            title: '李四',
            key: '0-0-0-1',
          },
          {
            title: '王五',
            key: '0-0-0-2',
          },
        ],
      },
      {
        title: '仓库部',
        key: '0-0-1',
        children: [
          {
            title: '张三',
            key: '0-0-1-0',
          },
          {
            title: '李四',
            key: '0-0-1-1',
          },
          {
            title: '王五',
            key: '0-0-1-2',
          },
        ],
      },
    ],
  },
];
export default defineComponent({
  setup(props,context) {
    const onContextMenuClick = (treeKey, menuKey) => {
      // console.log(`treeKey: ${treeKey}, menuKey: ${menuKey}`);
    };

    const tree_click = (checkedKeys, e) => {
      // console.log(e.eventKey, checkedKeys)
     //  e.eventKey  选中的key
      context.emit("tree_click:tree_click", e.eventKey)
    }

    const tree_data = reactive({
      treeList: []
    });

    const expandedKeys = ref(['0-0-0', '0-0-1']);
    watch(expandedKeys, () => {
      // console.log('expandedKeys', expandedKeys);
    });

    // function handle_tree_data(data) {
    //   for (let i = 0; i < data.length; i++) {
    //     let item = data[i]
    //     tree_data.treeList.push({
    //       key: item.orgId,
    //       title: item.orgName,
    //       children:
    //     })
    //
    //   }
    // }
    //
    // function handle_children(data){
    //   if (data) {
    //     handle_children(data)
    //   }
    // }

    //处理树结构 get_org_tree_list
    const handle_tree = async () => {
      const res = await get_org_tree_list_left({})
      console.log("机构列表", res)
      if (res.code === 1) {
        tree_data.treeList = res.data
        console.log("treeList", tree_data.treeList)
      }
    }

    handle_tree()

    return {
      treeData,
      onContextMenuClick,
      expandedKeys,
      tree_data,
      handle_tree,
      tree_click
    };
  },
});
</script>
